import os
import traceback
import uuid
import time
import datetime

from django.shortcuts import render
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from .models import MemoryUser, Memory, Reply

from .util.classifyByDate import classifyMemory
# Create your views here.
def home(request):
    return render(request, 'memory_storage/index_home.html')

def main(request):
    return render(request, 'memory_storage/main/main.html')

def register(request):
    """
    跳转到注册页面
    :param request:
    :return:
    """
    return render(request, 'memory_storage/register/register.html')

def get_user_pic(request):
    """
    获取用户头像以及昵称
    """
    data = {}
    user_id = request.POST.get('user_id')
    #print('get_user_pic user_id=', user_id)
    try:
        user = MemoryUser.objects.get(user_id=user_id)
        if user:
            data.update({
                'pic': user.pic,
                'username': user.username
            })
            #print('get_user_pic data=',data)
            return JsonResponse({"result": True, "code": 200, "data": data})
        else:
            return JsonResponse({"result": False, "code": 101, "message": "用户不存在"})
    except Exception as e:
        traceback.print_exc()
        return JsonResponse({"result": False, "code": 101, "message": "获取用户头像出错"})




def personal_center(request):
    """
    个人中心
    """
    user_id = request.GET['user_id']
    #print('personal_center user_id = ',user_id)
    try:
        user = MemoryUser.objects.get(user_id=user_id)
        return render(request, 'memory_storage/person/personal_center.html', {"user": user})
    except Exception as e:
        traceback.print_exc()

def my_collect(request):
    """我的收藏"""
    user_id = request.GET['user_id'] # 当前已经登录的用户
    keyword = request.GET.get("keyword")  # 用于将来可能的搜索功能
    page = request.GET.get("page", "1")

    print('my_collect user_id = ', user_id)
    print('my_collect keyword = ', keyword)
    print('my_collect page = ', page)





    if not keyword:
        memories = Memory.objects.filter( id__in=Reply.objects.filter(author=user_id, type="2").values('memory') )
        print(memories)
        #memories = Memory.objects.filter( Q(Replay__author=user_id) | Q(Replay__type=2) )
    else:
        memories = Memory.objects.filter(Q(memory_title__contains=keyword) | Q(memory_content__contains=keyword))

    p = Paginator(memories, 4)
    memories = p.get_page(page)

    return render(request, 'memory_storage/person/my_collect/my_collect.html',
                  {
                      "memories": memories,
                      "keyword": keyword,
                      "page": int(page),
                      "page_range": p.page_range,
                      "user_id": user_id
                  })


def public_square(request):
    """
    记忆广场
    """
    user_id = request.GET['user_id']

    keyword = request.GET.get("keyword")
    page = request.GET.get("page", "1")


    #print('public_square user_id = ', user_id)
    print('public_square keyword = ', keyword)
    #print('public_square page = ', page)


    if not keyword:
        memories = Memory.objects.filter(Q(status=0))
    else:
        memories = Memory.objects.filter(Q(memory_title__contains=keyword) | Q(memory_content__contains=keyword))

    p = Paginator(memories, 4)
    memories = p.get_page(page)

    return render(request, 'memory_storage/public_square/public_square.html',
    {
        "memories": memories,
        "keyword": keyword,
        "page": int(page),
        "page_range": p.page_range,
        "user_id": user_id
    })

def registerNewUser(request):
    """
    注册用户
    :param request:
    :return:
    """
    # 利用毫秒级时间戳生成user_id保证其唯一性
    t = time.time()
    user_id = str( round( t * 1000 ) )
    try:
        username = request.POST.get('username',"")
        password = request.POST.get('password',"")

        #是否支持昵称重名
        #if MemoryUser.objects.get(username=username):
        #    return JsonResponse({"result": False, "code": 101, "message": "该昵称已被使用"})

        #print('registerNewUser-username = ',username)
        #print('registerNewUser-password = ', password)

        kwargs = {
            "user_id": user_id,
            "username": username,
            "password": password,
        }
        MemoryUser.objects.create(**kwargs)
        return JsonResponse({"result": True, "code": 200, "message": "注册成功"})
    except Exception as e:
        traceback.print_exc()
        return JsonResponse({"result": False, "code": 101, "message": "注册出错"})


def login(request):
    try:
        username = request.POST.get('username',"")
        password = request.POST.get('password',"")
        print('username = ',username)
        userInfo = MemoryUser.objects.get( Q(username=username) & Q(password=password) )
        if userInfo:
            return JsonResponse({"result": True, "code": 200, "message": "登录成功", "user_id": userInfo.user_id})
    except Exception as e:
        traceback.print_exc()
        return JsonResponse({"result": False, "code": 101, "message": "用户名或密码错误"})

def save_memory_info(request):
    """
    保存记忆碎片数据
    """
    #print('save_memory_info')
    try:
        memory_title = request.POST.get('memory_title')
        memory_content = request.POST.get('memory_content')
        memory_level = int(request.POST.get('memory_level'))

        # 该字段由数据库自行添加
        # create_time = request.POST.get('create_time')

        end_time = request.POST.get('end_time')

        user_id = request.POST.get('user_id')

        print("save_memory_info-user_id=",request.POST.get("user_id"))

        status = 0 if request.POST.get('status') == "false" else 1
        kwargs = {
            "memory_title": memory_title,
            "memory_content": memory_content,
            "memory_level": memory_level,

            "belonging_user": MemoryUser.objects.get(user_id=user_id),

            "end_time": end_time,
            "status": status,
        }
        #print('kwargs :',kwargs)
    except Exception as e:
        print(e)
        return JsonResponse({"result": False, "code": 101, "message": "参数获取错误", "error": str(e)})

    memory_id = request.POST.get("memory_id", None)
    if memory_id:
        # 修改
        try:
            Memory.objects.filter(id=memory_id).update(**kwargs)
        except Exception as e:
            print(e)
            return JsonResponse({"result": False, "code": 101, "message": "修改数据错误"})
    else:
        # 添加数据
        try:
            Memory.objects.create(**kwargs)
        except Exception as e:
            print(e)
            return JsonResponse({"result": False, "code": 101, "message": "保存数据错误"})
    return JsonResponse({"result": True, "code": 200, "message": "success"})

# 暂时未设置好
def upload_img(request):
    SAVE_DIR = 'static/memoryImage/img'

    try:
        myFileName =  request.FILES.get('myFileName',"")
        belonging_user =  request.POST.get('belonging_user'),

        print(myFileName.name)

        if myFileName:
            if myFileName.name.split(".") == 0 or myFileName.name.split(".") == 1:
                return JsonResponse({"result": False, "code": 101,
                             "message": "⽂件名错误，⽆扩展名称或⽆⽂件名称"})

            if not os.path.exists(SAVE_DIR):
                os.makedirs(SAVE_DIR)
            new_file_name = "{}.{}".format(str(uuid.uuid4()), ".".join(myFileName.name.split(".")[1:]))

            if myFileName:
                with open(os.path.join(SAVE_DIR, new_file_name), 'wb') as w:
                    for block in myFileName.chunks():
                        w.write(block)
            file_url = str(os.path.join(SAVE_DIR, new_file_name))

            print("file_url = " + file_url)

            #print(myFileName.name)
            return JsonResponse({'url': file_url})
    except Exception as e:
        traceback.print_exc()


def get_memory_info(request):
    """
    获取用户所有记忆碎片
    :param request:
    :return:
    """
    kwargs = {}

    if request.POST.get("user_id"):
       kwargs.update({"belonging_user__user_id": request.POST.get("user_id")})

    #print("user_id=",request.POST.get("user_id"))
    memorys = Memory.objects.filter(**kwargs)

    result_data = []
    data_classified = {}
    for memory_item in memorys:
        # print(memory_item.create_time.strftime("%Y-%m-%d %H:%M:%S"))
        result_data.append({

            "belonging_user": memory_item.belonging_user.user_id,
            "memory_id": memory_item.id,
            "memory_title": memory_item.memory_title,
            "memory_content": memory_item.memory_content,
            "memory_level": memory_item.memory_level,
            "is_modify": memory_item.is_modify,
            "status": memory_item.status,
            "end_time": memory_item.end_time.strftime("%Y-%m-%d"),
            "create_time": memory_item.create_time.strftime("%Y-%m-%d")
        })
        data_classified = classifyMemory(result_data)
    #print(data_classified)
    return JsonResponse({
        "result": True,
        "code": 200,
        "data": result_data,
        "classification": data_classified
    })

def save_user_info(request):
    kwargs = {}
    SAVE_DIR = 'static/memoryImage/userImage'
    try:
        user_id = request.GET['user_id']
        email = request.POST.get('email','')
        username = request.POST.get('username')
        motto = request.POST.get('motto','')
        password = request.POST.get('password','')
        pic = request.FILES.get('pic', '')

        #print(user_id)

        if pic:
            if pic.name.split(".") == 0 or pic.name.split(".") == 1:
                return JsonResponse({"result": False, "code": 101,
                                     "message": "⽂件名错误，⽆扩展名称或⽆⽂件名称"})

            if not os.path.exists(SAVE_DIR):
                os.makedirs(SAVE_DIR)
            new_pic_name = "{}.{}".format(str(uuid.uuid4()), ".".join(pic.name.split(".")[1:]))

            if pic:
                with open(os.path.join(SAVE_DIR, new_pic_name), 'wb') as w:
                    for block in pic.chunks():
                        w.write(block)
            pic_url = str(os.path.join(SAVE_DIR, new_pic_name))

            pic_get_url = "{}".format( pic_url.split('static/')[1] )

            kwargs.update({ "pic": pic_get_url })

            # memoryImage/userImage\bec5b4b4-29f3-448d-a67e-522aa57a1bc7.png
            #print(pic_get_url)

        kwargs.update({
            "email": email,
            "username": username,
            "motto": motto,
            "password": password,
        })
        #print('save_user_info request.user.username=',request.user.username)
        #print('save_user_info kwargs=',kwargs)

        user = MemoryUser.objects.filter(user_id=user_id)
        user.update(**kwargs)

        return JsonResponse({"result": True, "code": 200, "message": "保存成功"})
    except Exception as e:
        traceback.print_exc()
        return JsonResponse({"result": False, "code": 101, "message": "修改出错"})


def like(request):

    # 即为当前用户
    author = request.POST.get("author", "anonymous")
    memory_id = request.POST.get("memory_id")
    try:

        liked = Reply.objects.filter(author=author, memory=memory_id, type="0")

        if liked:
            liked.delete()
            return JsonResponse({"result": True, "code": 200, "message": "取消点赞"})
        else:
            Reply.objects.create(author=author, memory=Memory.objects.get(id=memory_id), type="0")
            return JsonResponse({"result": True, "code": 200, "message": "点赞成功" })
    except Exception as e:
        traceback.print_exc()
        return JsonResponse({"result": False, "code": 101, "message": "点赞失败" })


def dislike(request):

    # 即为当前用户
    author = request.POST.get("author", "anonymous")
    memory_id = request.POST.get("memory_id")

    try:
        disliked = Reply.objects.filter(author=author, memory=memory_id, type="1")
        if disliked:
            disliked.delete()
            return JsonResponse({"result": True, "code": 200, "message": "已取消点踩" })
        else:
            Reply.objects.create(author=author, memory=Memory.objects.get(id=memory_id), type="1")
            return JsonResponse({"result": True, "code": 200, "message": "你点了一个踩" })
    except Exception as e:
        traceback.print_exc()
        return JsonResponse({"result": False, "code": 101, "message": "点踩失败" })

def collect(request):

    # 即为当前用户
    author = request.POST.get("author")
    memory_id = request.POST.get("memory_id")
    print(author)
    if not author:
        return JsonResponse({"result": False, "code": 101, "message": "未登录不能收藏"})


    try:

        collected = Reply.objects.filter(author=author, memory=memory_id, type="2")

        if collected:
            collected.delete()
            return JsonResponse({"result": True, "code": 200, "message": "取消收藏"})
        else:
            Reply.objects.create(author=author, memory=Memory.objects.get(id=memory_id), type="2")
            return JsonResponse({"result": True, "code": 200, "message": "收藏成功" })
    except Exception as e:
        traceback.print_exc()
        return JsonResponse({"result": False, "code": 101, "message": "收藏失败" })

def get_count_info(request):
    """
    获取一个记忆碎片点赞，点踩，收藏的数据
    """
    memory_id = request.POST.get('memory_id')
    data = {}
    if not memory_id:
        return JsonResponse({"result": False, "code": 101, "message": "未获取到当前碎片信息"})

    try:
        count_liked = Reply.objects.filter(memory=memory_id, type="0").count()
        count_disliked = Reply.objects.filter(memory=memory_id, type="1").count()
        count_collected = Reply.objects.filter(memory=memory_id, type="2").count()

        data = {
            'count_liked': count_liked,
            'count_disliked': count_disliked,
            'count_collected': count_collected
        }

        return JsonResponse({"result": True, "code": 101, "message": "获取统计信息失败", "data": data})
    except Exception as e:
        traceback.print_exc()
        return JsonResponse({"result": False, "code": 101, "message": "获取统计信息失败"})